import java.awt.Color;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.util.ArrayList;
import java.util.Map;

import com.speljohan.rsbot.bot.Bot;
import com.speljohan.rsbot.event.events.ServerMessageEvent;
import com.speljohan.rsbot.event.listeners.PaintListener;
import com.speljohan.rsbot.event.listeners.ServerMessageListener;
import com.speljohan.rsbot.script.Constants;
import com.speljohan.rsbot.script.Methods;
import com.speljohan.rsbot.script.Script;
import com.speljohan.rsbot.script.wrappers.RSCharacter;
import com.speljohan.rsbot.script.wrappers.RSInterface;
import com.speljohan.rsbot.script.wrappers.RSObject;
import com.speljohan.rsbot.script.wrappers.RSTile;

public class LumbFlaxWhirler extends Script implements PaintListener,
		ServerMessageListener {
	int count = 0;
	int currentBSCost;
	double currentBSCost2;
	int count2 = 0;
	int currentFlaxCost;
	double currentFlaxCost2;
	int count3 = 0;
	int total;
	int decimalPlace = 2;

	boolean proggy = false;

	// BigDecimal sold = new BigDecimal(count);
	// sold = sold.setScale(decimalPlace,BigDecimal.ROUND_UP);

	long startTime = System.currentTimeMillis();
	int stringsBanked = 0;
	int bankFail = 0;
	int wlkedtobank = 0;

	boolean tabChecked = false;

	final int FLAX_ID = 1779;
	final int BOW_STRING_ID = 1777;
	final int DOOR_CLOSE_ID = 36844;
	final int BOW_STRING_CHILD_ID = 17;
	final int FLAX_CHILD_ID = 17;
	final int SPINNING_WHEEL_ID = 36785;
	final int SPINNING_INTERFACE_ID = 459;
	final int BANK_ID = 4907;
	final int BANK_OBJ = 36831;

	final Color BG = new Color(123, 123, 123, 100);
	final Color GREEN = new Color(0, 255, 0, 255);
	final Color RED = new Color(255, 0, 0, 255);
	final Color WHITE = new Color(255, 255, 255, 255);
	final Color WHITE2 = new Color(200, 200, 200, 200);

	final RSTile DOOR_CLOSE_TILE = new RSTile(3207, 3214);
	final RSTile STAIRCASE_TILE = new RSTile(3205, 3208);
	final RSTile STAIRCASE_TILE2 = new RSTile(3204, 3208);
	final RSTile BANK_TILE = new RSTile(3208, 3221);

	public boolean scriptEnded = false;

	public boolean msgSent = false;

	boolean spellCasted = false;

	RSTile current2 = null;

	// Alarm for the random
	public void alarm() {
		for (int i1 = 0; i1 < 5; i1++) {
			Toolkit.getDefaultToolkit().beep();
			try {
				Thread.sleep(5000);
			} catch (final InterruptedException e) {
			}
		}
	}

	public int antiBan() {
		final int GambleInt = random(1, 7);

		if (GambleInt == 1) {
			wait(random(2000, 5000));
		}
		// A more human mouse movement.
		if (GambleInt == 2) {
			log("Moving Mouse.");
			int dist = random(5, 50);
			if (random(0, 10) == 0) {
				dist += random(250, 400);
			}
			final int x = Bot.getClient().getMouseX();
			final int y = Bot.getClient().getMouseY();
			int moveX = random(0, dist) - dist / 2;
			int moveY = random(0, dist) - dist / 2;
			if (moveX + x < 0) {
				moveX = x * -1 + 5;
			}
			if (moveY + y < 0) {
				moveY = y * -1 + 5;
			}
			if (moveX + x >= 750) {
				moveX = 750 - x - 5;
			}
			if (moveY + y >= 750) {
				moveY = 750 - y - 5;
			}
			moveMouse(x, y, moveX, moveY);
			return random(1000, 1500);
		}

		if (GambleInt == 3) {
			log("Checking your Friends list.");
			openTab(Constants.TAB_FRIENDS);
			tabChecked = true;
			wait(random(1500, 7000));
			if (tabChecked && getCurrentTab() == Constants.TAB_FRIENDS) {
				log("Friends list checked, going back to inventory.");
				openTab(Constants.TAB_INVENTORY);
				tabChecked = false;
			}
		}

		// if (GambleInt == 4) {
		// Checks random stat can slow down the script at rare occassions
		// log("Checking your Crafting.");
		// if ( getCurrentTab( ) != TAB_STATS ) {
		// openTab( TAB_STATS );
		// }
		// moveMouse(609,357,48,23);
		// tabChecked = true;
		// wait(random(700,2000));
		// if(tabChecked && getCurrentTab() == TAB_STATS) {
		// openTab(TAB_INVENTORY);
		// tabChecked = false;
		// log("Crafting checked, going back to inventory.");
		// }
		// }

		if (GambleInt == 5) {
			// Sets the camera to fully up, need a way to detect if the camera
			// is at the right position though.
			log("Random Setting Max Altitude.");
			setMaxAltitude();
		}
		if (GambleInt == 6) {
			// Random mouse movement, Left and right.
			log("Random Compass Movement.");
			moveCompass();
		}
		if (GambleInt == 7) {
			final RSCharacter closePlayer = getNearestPlayerByLevel(3, 138);
			if (closePlayer != null) {
				clickMouse(closePlayer.getScreenLocation(), false);
				log("Randomly clicking a player.");
				wait(random(500, 1500));
				atMenu("Cancel");
			}
		}
		if (GambleInt == 8) {
			log("Examining a random object.");
			final int[] ids = { 37015, 35878, 36779, 33795, 36785, 444, 442,
					2732 };
			while (true) {
				final RSObject examineOb = findObject(ids[random(0, 8)]);
				if (examineOb != null) {
					atObject(examineOb, "xamine");
				}
			}
		}

		return random(3000, 5000);
	}

	public RSTile bankTile() {
		return new RSTile(random(3207, 3210), random(3218, 3220));
	}

	public int bowstringCount() {
		return getInventoryCount(BOW_STRING_ID);
	}

	public void deathWalk() {
		if (getPlane() != 0 && distanceTo(new RSTile(3211, 3219)) <= 20) {
			return;
		}
		if (distanceTo(new RSTile(3211, 3219)) > 20) {
			if (getMyPlayer().getAnimation() != 1722
					|| getMyPlayer().getAnimation() != 1723
					|| getMyPlayer().getAnimation() != 1724
					|| getMyPlayer().getAnimation() != 1725
					|| getMyPlayer().getAnimation() != 2798
					|| getMyPlayer().getAnimation() != 2799
					|| getMyPlayer().getAnimation() != 2800
					|| getMyPlayer().getAnimation() != 3195
					|| getMyPlayer().getAnimation() != 3644
					|| getMyPlayer().getAnimation() != 4847
					|| getMyPlayer().getAnimation() != 4848
					|| getMyPlayer().getAnimation() != 4849) {
				log("Character is lost; attempting to use Home Teleport.");
				if (bank.getInterface().isValid()) {
					clickMouse(490, 34, true);
				} else {
					castSpell(1);
					spellCasted = true;
					if (getMyPlayer().getAnimation() == 1722 && spellCasted) {
						wait(random(15000, 17000));
					} else {
						wait(random(100, 300));
					}
					if (spellCasted && distanceTo(new RSTile(3211, 3219)) > 6) {
						log("Spell cast failed, attempting to walk/run back.");
						spellCasted = false;
						alarm();
					}
					if (spellCasted && distanceTo(new RSTile(3221, 3218)) < 7) {
						log("Successfully teleported, resuming script.");
						spellCasted = false;
					}
					return;
				}
			}
		}
	}

	public int flaxCount() {
		return getInventoryCount(FLAX_ID);
	}

	public RSTile[] generatePath(final int destinationX, final int destinationY) { // Most
		// credits
		// go to
		// aftermath...
		// I
		// asked
		// for a
		// theory
		// and
		// he
		// gives
		// me
		// the
		// whole
		// method.
		// ~Mike
		int startX = getMyPlayer().getLocation().getX();
		int startY = getMyPlayer().getLocation().getY();
		double dx, dy;
		final ArrayList<RSTile> list = new ArrayList<RSTile>();

		list.add(new RSTile(startX, startY));
		while (Math.hypot(destinationY - startY, destinationX - startX) > 8) {
			dx = destinationX - startX;
			dy = destinationY - startY;
			final int gamble = random(14, 17);
			while (Math.hypot(dx, dy) > gamble) {
				dx *= .95;
				dy *= .95;
			}
			startX += (int) dx;
			startY += (int) dy;
			list.add(new RSTile(startX, startY));
		}
		list.add(new RSTile(destinationX, destinationY));
		return list.toArray(new RSTile[list.size()]);
	}

	public RSTile[] generatePath(final RSTile tile) {
		return generatePath(tile.getX(), tile.getY());
	}

	public int getAngleToCoordinates(final int x2, final int y2) {
		final int x1 = getMyPlayer().getLocation().getX();
		final int y1 = getMyPlayer().getLocation().getY();
		final int x = x1 - x2;
		final int y = y1 - y2;
		double angle = Math.toDegrees(Math.atan2(x, y));
		if (x == 0 && y > 0) {
			angle = 180;
		}
		if (x < 0 && y == 0) {
			angle = 90;
		}
		if (x == 0 && y < 0) {
			angle = 0;
		}
		if (x < 0 && y == 0) {
			angle = 270;
		}
		if (x < 0 && y > 0) {
			angle += 270;
		}
		if (x > 0 && y > 0) {
			angle += 90;
		}
		if (x < 0 && y < 0) {
			angle = Math.abs(angle) - 180;
		}
		if (x > 0 && y < 0) {
			angle = Math.abs(angle) + 270;
		}
		if (angle < 0) {
			angle = 360 + angle;
		}
		if (angle >= 360) {
			angle -= 360;
		}
		return (int) angle;
	}

	public String getAuthor() {
		return "Venom - Based off Mike's Lumby Flax Spinner";
	}

	public String getName() {
		return "Lumbridge Flax Whirler";
	}

	public String getScriptCategory() {
		return "Crafting";
	}

	public String getScriptDescription() {
		String html = "";

		html += "<html>\n";
		html += "<body>\n";
		html += "<h2>" + getName() + " v" + getVersion() + "</h2><br>\n";
		html += "By Venom, based off Mike's Lumby Flax Spinner<br><br>";
		html += "<b>SETTINGS:</b><br>";
		html += "<b>What is the current price of Bow Strings?</b><br>";
		html += "<input type=\"text\" name=\"count\" value=\"190\"><br>";
		html += "<b>If bought flax, how much did you buy each for? Leave 0 if you picked yourself.</b><br>";
		html += "<input type=\"text\" name=\"flaxcost\" value=\"0\"><br>";
		html += "<b>How many flax do you wish to string?</b><br>";
		html += "<input type=\"text\" name=\"wanttostring\" value=\"1000\"><br>";
		html += "<br>";
		html += "</body>\n";
		html += "</html\n";

		return html;
	}

	public String getTopText() {
		return getMenuItems().get(0).toLowerCase();
	}

	public double getVersion() {
		return 3.0;
	}

	public boolean isDoorClosed() {
		/*
		 * if (getPlane() == 1 && !isInSpinningRoom()) { if
		 * (Calculations.canReach(spinningRoomTile(), true)) { return false; } }
		 * if (getPlane() == 1 && isInSpinningRoom()) { if
		 * (Calculations.canReach(staircaseTile(), true)) { return false; } }
		 */
		final RSObject door = getObjectAt(DOOR_CLOSE_TILE);
		if (door.getID() == DOOR_CLOSE_ID) {
			log("Door is closed.");
			return true;
		} else {
			return false;
		}
	}

	public boolean isDoorOpen() {
		/*
		 * if (getPlane() == 1 && !isInSpinningRoom()) { if
		 * (Calculations.canReach(spinningRoomTile(), true)) { return false; } }
		 * if (getPlane() == 1 && isInSpinningRoom()) { if
		 * (Calculations.canReach(staircaseTile(), true)) { return false; } }
		 */
		final RSObject door = getObjectAt(DOOR_CLOSE_TILE);
		if (door.getID() == 33868) {
			log("Door is open.");
			return true;
		} else {
			return false;
		}
	}

	public boolean isInBank() {
		final RSTile myLocation = getMyPlayer().getLocation();
		final int myX = myLocation.getX();
		final int myY = myLocation.getY();

		if (myX >= 3207 && myX <= 3210 && myY >= 3218 && myY <= 3220
				&& getPlane() == 2) {
			return true;
		}

		return false;
	}

	public boolean isInSpinningRoom() {
		final RSTile myLocation = getMyPlayer().getLocation();
		final int myX = myLocation.getX();
		final int myY = myLocation.getY();

		if (myX >= 3208 && myX <= 3212 && myY >= 3212 && myY <= 3217
				&& getPlane() == 1) {
			return true;
		}

		return false;
	}

	public void logoutFor(final int i) {
	}

	public int loop() {
		if (getMyPlayer().isMoving()) {
			antiBan();
		}
		try {
			final int height = getPlane();
			if (!RSInterface.getInterface(SPINNING_INTERFACE_ID).isValid()) {
				if (flaxCount() == 0) {
					atInterface(SPINNING_INTERFACE_ID, 12);
				} else if (!bank.getInterface().isValid()) {
					if (getEnergy() >= random(50, 99)) {
						setRun(true);
					}
				}
			}
			if (stringsBanked + getInventoryCount(BOW_STRING_ID) >= count3) {
				if (getInventoryCount(1779) > 0 || getInventoryCount(1777) > 0) {
					if (!msgSent) {
						log("Strung amount asked. Going to bank, then logging out and stopping script.");
						msgSent = true;
					}
					if (height == 1) {
						if (!walkToTile(staircaseTile())) { // Going upstairs to
							// bank then logging
							// out
							return random(300, 500);
						}
						if (!atTile(STAIRCASE_TILE, "Climb-up")) {
							turnToTile(STAIRCASE_TILE);
						}
					}
					if (!isInBank()) { // banking
						if (!bank.getInterface().isValid()
								&& distanceTo(new RSTile(3208, 3221)) < 4
								&& !scriptEnded) {
							if (!atTile(BANK_TILE, "Use-quickly")) {
								turnToTile(BANK_TILE);
								wait(random(800, 900));
							}
						}
						walkToTile(bankTile());
						return random(300, 500);
					}
					if (!bank.getInterface().isValid()
							&& distanceTo(new RSTile(3208, 3221)) < 4
							&& !scriptEnded) {
						if (!atTile(BANK_TILE, "Use-quickly")) {
							turnToTile(BANK_TILE);
							wait(random(300, 600));
						}
					}
					if (bank.getInterface().isValid()) { // just banking items
						// no withdrawing
						final int temp = bowstringCount();
						if (bank.depositAllExcept(FLAX_ID)) {
							stringsBanked += temp;
							clickMouse(false);
						}
						clickMouse(490, 34, true);
						scriptEnded = true;
					}
				} else {
					if (bank.getInterface().isValid()) {
						clickMouse(490, 34, true);
					}
					stopAllScripts();
				}
			}
			if (getPlane() == 0 || distanceTo(new RSTile(3211, 3219)) > 20
					&& !scriptEnded) {
				deathWalk();
			}
			if (getMyPlayer().getAnimation() == 894
					&& getCurrentTab() != Constants.TAB_INVENTORY) {
				openTab(Constants.TAB_INVENTORY);
				return random(3000, 7000);
			}
			if (getMyPlayer().getAnimation() == 894) {
				final int GambleInt2 = random(1, 5);
				if (GambleInt2 == 1 || GambleInt2 == 4 || GambleInt2 == 5) {
					log("Random mouse movement.");
					int dist = random(5, 50);
					if (random(0, 10) == 0) {
						dist += random(250, 400);
					}
					final int x = Bot.getClient().getMouseX();
					final int y = Bot.getClient().getMouseY();
					int moveX = random(0, dist) - dist / 2;
					int moveY = random(0, dist) - dist / 2;
					if (moveX + x < 0) {
						moveX = x * -1 + 5;
					}
					if (moveY + y < 0) {
						moveY = y * -1 + 5;
					}
					if (moveX + x >= 750) {
						moveX = 750 - x - 5;
					}
					if (moveY + y >= 750) {
						moveY = 750 - y - 5;
					}
					moveMouse(x, y, moveX, moveY);
					return random(1000, 20000);
				} else if (GambleInt2 == 2) {
					log("Checking your Crafting.");
					if (getCurrentTab() != Constants.TAB_STATS) {
						openTab(Constants.TAB_STATS);
					}
					moveMouse(609, 357, 48, 23);
					tabChecked = true;
					wait(random(4000, 8000));
					log("Crafting checked, going back to inventory.");
					if (tabChecked && getCurrentTab() == Constants.TAB_STATS) {
						openTab(Constants.TAB_INVENTORY);
						tabChecked = false;
					}
					return random(10000, 30000);
				} else if (GambleInt2 == 3) {
					log("Random compass movement during spinning.");
					moveCompass();
					return random(1000, 20000);
				}
			}
			if (height == 1 && !scriptEnded) { // flax level
				if (flaxCount() > 0 && !getMyPlayer().isInCombat()) {
					if (!isInSpinningRoom()) {
						if (isDoorClosed() && !getMyPlayer().isMoving()) {
							final RSObject door = getObjectAt(DOOR_CLOSE_TILE);
							// if (!walkToTile(outsideDoor())) {
							// return random(500, 700);
							// }
							if (!atTile(outsideDoor(), "Walk here")) {
								turnToTile(door.getLocation());
							}
							if (door == null || door.getID() != DOOR_CLOSE_ID) {
								return random(500, 1000);
							}
							turnToTile(door.getLocation());
							atDoor(door, "east", "Open");
							return random(300, 500);
						} else {
							// if (!walkToTile(spinningRoomTile())) {
							// return random(400,600);
							// }
							if (!atTile(spinningRoomTile(), "Walk here")) {
								turnToTile(spinningRoomTile());
							}
						}
					} else {
						for (int i = 0; i <= 10; i++) {
							if (getMyPlayer().getAnimation() != -1) {
								return random(300, 500);
							} else {
								wait(random(100, 150));
							}
						}
						if (flaxCount() == 0) {
							return random(300, 500);
						}
						if (RSInterface.getInterface(SPINNING_INTERFACE_ID)
								.isValid()) {
							atInterface(SPINNING_INTERFACE_ID,
									BOW_STRING_CHILD_ID, "all");
							return random(100, 200);
						}
						final RSObject spinner = findObject(SPINNING_WHEEL_ID);
						if (spinner == null) {
							return random(300, 500);
						}
						if (!atObject(spinner, "Spin Spinning Wheel")) {
							turnToTile(spinner.getLocation());
						}
						return random(200, 400);
					}
				} else {
					if (isInSpinningRoom()) {
						if (isDoorClosed()) {
							final RSObject door = getObjectAt(DOOR_CLOSE_TILE);
							if (door == null || door.getID() != DOOR_CLOSE_ID) {
								return random(300, 500);
							}
							turnToTile(door.getLocation());
							atDoor(door, "east", "Open");
							return random(300, 500);
						}
						if (!walkToTile(staircaseTile())) {
							return random(300, 500);
						}
					}
					if (!atTile(STAIRCASE_TILE, "Climb-up")) {
						turnToTile(STAIRCASE_TILE);
					}
				}
			}
			if (height == 2 && !scriptEnded) { // bank level
				if (flaxCount() > 0) {
					if (!walkToTile(staircaseTile())) {
						return random(300, 500);
					}
					if (!atTile(STAIRCASE_TILE, "Climb-down")) {
						turnToTile(STAIRCASE_TILE);
					}
				} else {
					if (!isInBank()) {
						if (!bank.getInterface().isValid()
								&& distanceTo(new RSTile(3208, 3221)) < 4) {
							if (!atTile(BANK_TILE, "Use-quickly")) {
								turnToTile(BANK_TILE);
								wait(random(800, 900));
							}
						}
						walkToTile(bankTile());
						return random(300, 500);
					}
					if (!bank.getInterface().isValid()
							&& distanceTo(new RSTile(3208, 3221)) < 4) {
						if (!atTile(BANK_TILE, "Use-quickly")) {
							turnToTile(BANK_TILE);
							wait(random(300, 600));
						}
					}
					// RSObject bankbooth = findObject(BANK_OBJ);
					// if (distanceTo(new RSTile(3208, 3221)) < 4 && bank !=
					// null && !RSInterface.getInterface( INTERFACE_BANK
					// ).isValid()) {
					// atObject(bankbooth, "Use-Quickly");
					// wait(random(1000,2000));
					// }
					/*
					 * if (!atNPC(banker, "Bank Bank Tutor")) { //
					 * turnToTile(banker.getLocation()); }
					 */
					if (getInterface(109).isValid()) {
						if (!atInterface(109, 13, "close")) {
							return random(300, 500);
						}
					}
					if (bank.getInterface().isValid()
							&& !getInterface(109).isValid() && !scriptEnded) {
						final int temp = bowstringCount();
						if (bank.depositAllExcept(FLAX_ID)) {
							stringsBanked += temp;
							moveMouse(48, 101, 15, 15);
							// atInterface(762,
							// FLAX_CHILD_ID, "all");
							if (!getTopText().contains("flax")) {
								bankFail++;
								if (bankFail >= 30) {
									log("Banking failed. Possibly ran out of flax!");
									return -1;
								}
								return random(300, 500);
							}
							clickMouse(false);
							if (atMenu("Withdraw-All Flax")) {
								bankFail = 0;
								return random(300, 400);
							}
						}
						return random(300, 500);
					}
				}
			}
			if (height == 0 && !scriptEnded) {
				final RSObject stairs = getObjectAt(STAIRCASE_TILE2);
				if (!walkToTile(staircaseTile2())) {
					return random(7500, 8000);
				}
				turnToTile(stairs.getLocation());
				atTile(STAIRCASE_TILE2, "Climb-up");
				return random(200, 300);
				// if (!atTile(STAIRCASE_TILE, "Climb-up")) {
				// }
			}
			// Runaway if in combat
			if (getMyPlayer().isInCombat()) {
				log("Engaged in combat, running away!");
				if (height == 2) {
					if (!walkToTile(staircaseTile())) {
						return random(300, 500);
					}
					if (!atTile(STAIRCASE_TILE, "Climb-down")) {
						turnToTile(STAIRCASE_TILE);
					}
				}
				if (height == 1) {
					if (isInSpinningRoom()) {
						if (isDoorClosed()) {
							final RSObject door = getObjectAt(DOOR_CLOSE_TILE);
							if (door == null || door.getID() != DOOR_CLOSE_ID) {
								return random(300, 500);
							}
							turnToTile(door.getLocation());
							atDoor(door, "east", "Open");
							return random(300, 500);
						}
						if (!walkToTile(staircaseTile())) {
							return random(300, 500);
						}
					}
					if (!atTile(STAIRCASE_TILE, "Climb-up")) {
						turnToTile(STAIRCASE_TILE);
					} else {
						if (!atTile(STAIRCASE_TILE, "Climb-up")) {
							turnToTile(STAIRCASE_TILE);
						}
					}
				}
				alarm();
			}
		} catch (final Exception e) {
			e.printStackTrace();
		}
		return random(300, 500);
	}

	private void moveCompass() {
		final char[] CAMERA = { java.awt.event.KeyEvent.VK_LEFT,
				java.awt.event.KeyEvent.VK_RIGHT };
		int turns = 1;
		if (random2(100) < random2(20)) {
			turns += random2(2);
		}
		for (int i = 0; i < turns; i++) {
			final char c = CAMERA[random2(CAMERA.length)];
			Bot.getInputManager().pressKey(c);
			wait(random2(2000));
			Bot.getInputManager().releaseKey(c);
		}
	}

	public RSTile nextTile2(final RSTile[] path, final int maxDist) {
		final RSTile cur = getMyPlayer().getLocation();
		for (int i = path.length - 1; i >= 0; i--) {
			if (Methods.distanceBetween(cur, path[i]) <= maxDist) {
				return path[i];
			}
		}
		return null;
	}

	public void onFinish() {
		Bot.getEventManager().removeListener(PaintListener.class, this);
		Bot.getEventManager().removeListener(ServerMessageListener.class, this);
		long millis = System.currentTimeMillis() - startTime;
		final long seconds2 = millis / 1000;
		final long hours = millis / (1000 * 60 * 60);
		millis -= hours * 1000 * 60 * 60;
		final long minutes = millis / (1000 * 60);
		millis -= minutes * 1000 * 60;
		final long seconds = millis / 1000;
		String hoursString = "";
		String minutesString = "";
		String secondsString = seconds + "";
		String type = "seconds";
		if (minutes > 0) {
			minutesString = minutes + ":";
			type = "minutes";
		}
		if (hours > 0) {
			hoursString = hours + ":";
			type = "hours";
		}
		if (minutesString.length() == 1) {
			minutesString = "0" + minutesString;
		}
		if (hoursString.length() == 1) {
			hoursString = "0" + hoursString;
		}
		if (secondsString.length() == 1) {
			secondsString = "0" + secondsString;
		}
		msgSent = false;
		log("Strings banked, logging out now.");
		log("SCRIPT SUMMARY:");
		log("Ran for " + hoursString + minutesString + secondsString + " "
				+ type + ".");
		log(stringsBanked + getInventoryCount(BOW_STRING_ID) + " Flax Spun.");
		if (seconds2 != 0) {
			log("Averaged "
					+ (stringsBanked + getInventoryCount(BOW_STRING_ID)) * 3600
					/ seconds2 + " Strings per hour.");
		}
		log("Experience gained: "
				+ (stringsBanked + getInventoryCount(BOW_STRING_ID)) * 15 + ".");
		if (currentFlaxCost == 0) {
			log("Money made: "
					+ (stringsBanked + getInventoryCount(BOW_STRING_ID))
					* currentBSCost + " gp.");
		} else {
			log("Money made (minus Flax bought cost): "
					+ (stringsBanked + getInventoryCount(BOW_STRING_ID))
					* (currentBSCost - currentFlaxCost) + " gp. "/*
																 * +
																 * ((currentBSCost2
																 * -
																 * currentFlaxCost
																 * ) /
																 * currentFlaxCost
																 * - 1) * 100 +
																 * "% Profit."
																 */);
		}
	}

	public void onRepaint(final Graphics g) {
		if (isLoggedIn() && proggy == true) {
			long millis = System.currentTimeMillis() - startTime;
			final long seconds2 = millis / 1000;
			final long hours = millis / (1000 * 60 * 60);
			millis -= hours * 1000 * 60 * 60;
			final long minutes = millis / (1000 * 60);
			millis -= minutes * 1000 * 60;
			final long seconds = millis / 1000;
			String hoursString = "";
			String minutesString = "";
			String secondsString = seconds + "";
			String type = "seconds";
			if (minutes > 0) {
				minutesString = minutes + ":";
				type = "minutes";
			}
			if (hours > 0) {
				hoursString = hours + ":";
				type = "hours";
			}
			if (minutesString.length() == 1) {
				minutesString = "0" + minutesString;
			}
			if (hoursString.length() == 1) {
				hoursString = "0" + hoursString;
			}
			if (secondsString.length() == 1) {
				secondsString = "0" + secondsString;
			}
			final int x = 15;
			int y = 210;
			// g.setColor(BG);
			// g.fill3DRect(14, 25, 210, 165, true);
			g.setColor(WHITE2);
			g.drawString(getName() + " v" + getVersion(), x, y += 15);
			g.drawString("Running for " + hoursString + minutesString
					+ secondsString + " " + type + ".", x, y += 15);
			g.setColor(WHITE);
			g.drawString(stringsBanked + getInventoryCount(BOW_STRING_ID)
					+ " Flax Spun.", x, y += 20);
			g
					.drawString(
							"Amount left to string: "
									+ (total - (stringsBanked + getInventoryCount(BOW_STRING_ID)))
									+ ".", x, y += 15);
			if (seconds2 != 0) {
				g.drawString("Averaging "
						+ (stringsBanked + getInventoryCount(BOW_STRING_ID))
						* 3600 / seconds2 + " Strings per hour.", x, y += 15);
			}
			g.drawString("Experience gained: "
					+ (stringsBanked + getInventoryCount(BOW_STRING_ID)) * 15
					+ ".", x, y += 15);
			if (currentFlaxCost == 0) {
				g.drawString("Money made: "
						+ (stringsBanked + getInventoryCount(BOW_STRING_ID))
						* currentBSCost + " gp.", x, y += 20);
			} else {
				g.drawString("Money made (minus Flax bought cost): "
						+ (stringsBanked + getInventoryCount(BOW_STRING_ID))
						* (currentBSCost - currentFlaxCost) + " gp. "/*
																	 * +((
																	 * currentBSCost2
																	 * -
																	 * currentFlaxCost
																	 * ) /
																	 * currentFlaxCost
																	 * - 1) *
																	 * 100 +
																	 * "% Profit."
																	 */, x,
						y += 20);
			}
		}
	}

	public boolean onStart(final Map<String, String> args) {
		scriptEnded = false;
		count = Integer.parseInt(args.get("count"));
		count2 = Integer.parseInt(args.get("flaxcost"));
		count3 = Integer.parseInt(args.get("wanttostring"));
		currentBSCost = count;
		currentBSCost2 = count;
		currentFlaxCost = count2;
		currentFlaxCost2 = count2;
		total = count3;

		log("-----Lumbridge Flax Spinner started.-----");
		log("-----SETTINGS-----");
		log("-----Current Bow String Price set at: " + currentBSCost
				+ " gp.-----");
		if (currentFlaxCost > 0) {
			log("-----Current Flax Price set at: " + currentFlaxCost
					+ " gp.-----");
			log("-----Amount difference: " + (currentBSCost - currentFlaxCost)
					+ " gp.-----");
			log("-----Stringing " + count3 + " flax. You will make "
					+ (count3 * currentBSCost - count3 * currentFlaxCost)
					+ " gp.-----");
			log("-----And gain " + total * 15 + " experience in Crafting.-----");
		} else {
			log("-----Picked own flax/no flax price set.-----");
			log("-----Stringing " + count3 + " flax, you will make " + count3
					* currentBSCost + " gp.-----");
			log("-----And gain " + total * 15 + " experience in Crafting.-----");
		}

		bankFail = 0;
		proggy = true;
		startTime = System.currentTimeMillis();
		stringsBanked = 0;
		return true;
	}

	public RSTile outsideDoor() {
		return new RSTile(random(3205, 3207), random(3212, 3216));
	}

	private int random2(final int i2) {
		return random(0, i2);
	}

	public void serverMessageRecieved(final ServerMessageEvent e) {
		// String message = e.getMessage().toLowerCase();
		// if (message.contains("You need to wait another ")
		// && message.contains(" to cast this spell.")) {
		// int num = Integer.parseInt(message.split(" ")[5]);
		// logoutFor(num * 1000 * 60 * 60);
		// }
	}

	public void setCameraRotation2(int degrees) {
		// Made by aftermath. Was suggested into SVN and i just added it into
		// here until somebody does the right thing
		final char left = 37;
		final char right = 39;
		char whichDir = left;
		int start = getCameraAngle();

		if (start < 180) {
			start += 360;
		}
		if (degrees < 180) {
			degrees += 360;
		}

		if (degrees > start) {
			if (degrees - 180 < start) {
				whichDir = right;
			}
		} else if (start > degrees) {
			if (start - 180 >= degrees) {
				whichDir = right;
			}
		}
		degrees %= 360;

		Bot.getInputManager().pressKey(whichDir);
		int timeWaited = 0;

		while (getCameraAngle() > degrees + 5 || getCameraAngle() < degrees - 5) {
			wait(10);
			timeWaited += 10;
			if (timeWaited > 500) {
				final int time = timeWaited - 500;

				if (time == 0) {
					Bot.getInputManager().pressKey(whichDir);
				} else if (time % 40 == 0) {
					Bot.getInputManager().pressKey(whichDir);
				}
			}
		}
		Bot.getInputManager().releaseKey(whichDir);
	}

	public void setMaxAltitude() {
		Bot.getInputManager().pressKey((char) 38);
		wait(random(500, 1000));
		Bot.getInputManager().releaseKey((char) 38);
	}

	public RSTile spinningRoomTile() {
		return new RSTile(random(3208, 3212), random(3214, 3212));
	}

	public RSTile staircaseTile() {
		return new RSTile(random(3205, 3207), random(3205, 3211));
	}

	public RSTile staircaseTile2() {
		return new RSTile(random(3206, 3207), random(3209, 3211));
	}

	public void turnToTile(final RSTile tile) {
		int angle = getAngleToCoordinates(tile.getX(), tile.getY());
		angle = angle + random(-20, 20);
		if (angle < 0) {
			angle = 360 + angle;
		}
		if (angle >= 360) {
			angle -= 360;
		}
		setCameraRotation2(angle);
	}

	public boolean walkPathMM2(final RSTile[] path, final int maxDist) {
		try {
			final RSTile next = nextTile(path, maxDist);
			if (next != null && !next.equals(current2)) {
				walkTileMM(next);
				current2 = next;
				return false;
			} else if (next != null && next.equals(current2)) {
				return false;
			}
		} catch (final Exception e) {
			return false;
		}
		return true;
	}

	public boolean walkToTile(final RSTile tile) {
		if (walkPathMM2(generatePath(tile), 17)) {
			return true;
		}

		return false;
	}
}